#!/usr/bin/env python3 
# -*- coding: UTF-8 -*-

import argparse
import difflib
import pandas as pd
import os

ILLEGAL_WORDS = ['支撑','学习','熟悉','开会','讨论','评审','保障','整理','梳理','工作量','项目资料','交接','-',',']
WORKLOAD_LENGTH_LIMIT = 20
SIMILARITY_LIMIT = 0.8

def Similarity(a, b):    
    return difflib.SequenceMatcher(None, a, b).ratio() 

class WorkloadChecker(object):
    def __init__(self):
        self._filepath = ""
        self._table_index = None 
        self._table = None
        self._workload_list = []

    def ReadExcel(self, filepath, index = 0):
        self._filepath = filepath
        self._filename = os.path.basename(filepath)
        self._table_index = index

        self._table = pd.read_excel(filepath, sheet_name=index)
        self.__ParseTable()

    def __ParseTable(self):

        for i, row in self._table.iterrows(): 
            workload_list = row.iloc[3].splitlines()

            for workload in workload_list:
                workload = workload.strip()

                if workload == "":
                    continue

                self._workload_list.append({
                    'index': i,
                    'name': row.iloc[0],
                    'workload': workload,
                })

    def CheckDuplicate(self):
        duplicate_workload= []

        for i in range(0, len(self._workload_list)):
            for j in range(i + 1, len(self._workload_list)):
                workload_term_1 = self._workload_list[i]
                workload_term_2 = self._workload_list[j]
                workload_1 = workload_term_1['workload']
                workload_2 = workload_term_2['workload']

                p = Similarity(workload_1, workload_2)
                if  p > SIMILARITY_LIMIT:
                    duplicate_workload.append("[{0}][{2}][{4}] 与: \n[{1}][{3}][{5}] 相似\n".format(workload_term_1['index'], workload_term_2['index'], 
                                         workload_term_1['name'], workload_term_2['name'], workload_1, workload_2))
                                
        return duplicate_workload

    def CheckIllegalWords(self):
        illegal_check_result = []

        for workload_term in self._workload_list:
            workload = workload_term['workload']
            result = ""

            for word in ILLEGAL_WORDS:
                if word in workload:
                    result += ("[%s] " % (word))
                
            if result != "":
                illegal_check_result.append("行号: [{0}], 工作内容：[{1}], 包含非法字符:{2}\n".format(workload_term['index'], workload, result))

        return illegal_check_result

    def CheckWorkloadLength(self):
        length_check_result = []

        for workload_term in self._workload_list:
            workload = workload_term['workload']

            if len(workload) < WORKLOAD_LENGTH_LIMIT:
                length_check_result.append("行号: [{0}], 工作内容：[{1}], 长度小于{2}\n".format(workload_term['index'], workload, WORKLOAD_LENGTH_LIMIT))

        return length_check_result 

                            
    def CheckDuplicateWithOther(self, other):
        duplicate_workload= []

        for i in range(0, len(self._workload_list)):
            for j in range(0, len(other._workload_list)):
                workload_term_1 = self._workload_list[i]
                workload_term_2 = other._workload_list[j]
                workload_1 = workload_term_1['workload']
                workload_2 = workload_term_2['workload']

                p = Similarity(workload_1, workload_2)
                if  p > 0.8:
                    duplicate_workload.append("[{6}][{8}][{0}][{2}][{4}] 与: \n[{7}][{9}][{1}][{3}][{5}] 相似\n".format(
                        workload_term_1['index'], workload_term_2['index'], 
                        workload_term_1['name'], workload_term_2['name'], 
                        workload_1, workload_2,
                        self._filename, other._filename, 
                        self._table_index, other._table_index))
                                
        return duplicate_workload
    
def CheckDuplicate(input_filepath):
    reader = WorkloadChecker()
    reader.ReadExcel(input_filepath)
    return reader.CheckDuplicate()

def CheckIllegalWords(input_filepath):
    reader = WorkloadChecker()
    reader.ReadExcel(input_filepath)

    result = reader.CheckWorkloadLength()
    result.extend(reader.CheckIllegalWords())
    return result 

def CheckDuplicateWithHistory(input_filepath, history_file_dir):
    input_checker = WorkloadChecker()
    input_checker.ReadExcel(input_filepath)

    result = input_checker.CheckWorkloadLength()
    result.extend(input_checker.CheckIllegalWords())
    result.extend(input_checker.CheckDuplicate())
    result.append("与历史文件进行对比:\n")

    for root, _, files in os.walk(history_file_dir, topdown=False):
        for file in files:
            history_filepath = os.path.join(root,file)

            if os.path.samefile(input_filepath, history_filepath) or os.path.splitext(file)[1] != ".xls":
                continue

            history_checker = WorkloadChecker()
            history_checker.ReadExcel(history_filepath)
            
            result.extend(input_checker.CheckDuplicateWithOther(history_checker))

    return result 

def ExportResultTxt(info_list, output_filepath):
    with open(output_filepath, mode="w+") as f:
        for info in info_list:
            print("%s\n"%(info),file = f)
    


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", dest = "input_file", help = "the file want to check.", default="工作量.xlsx")
    parser.add_argument("-d", dest = "output_duplicate_file", help = "where the duplicate check result file want to save.", default="")
    parser.add_argument("-w", dest = "output_illegal_words_file", help = "where the illegal words check result file want to save.", default="")

    args = parser.parse_args()
    output_duplicate_file = args.output_duplicate_file
    output_illegal_words_file = args.output_illegal_words_file

    if output_duplicate_file == "":
        output_duplicate_file = os.path.splitext(args.input_file)[0] + "-重复度.txt"

    if output_illegal_words_file == "":
        output_illegal_words_file = os.path.splitext(args.input_file)[0] + "-非法字符.txt"

    dup_list = CheckDuplicate(args.input_file)
    ExportResultTxt(dup_list, output_duplicate_file)

    ill_list = CheckIllegalWords(args.input_file)
    ExportResultTxt(ill_list, output_illegal_words_file)
